package com.wxzz.elearing.pay.wx.mini;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Pattern;

import org.springframework.web.multipart.MultipartFile;

import com.vdurmont.emoji.EmojiParser;

import net.coobird.thumbnailator.Thumbnails;
import ws.schild.jave.AudioAttributes;
import ws.schild.jave.AudioInfo;
import ws.schild.jave.Encoder;
import ws.schild.jave.EncodingAttributes;
import ws.schild.jave.MultimediaInfo;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.VideoAttributes;
import ws.schild.jave.VideoInfo;
import ws.schild.jave.VideoSize;

public class ShareFunction {
    public static boolean strIsNull(String val) {
        if (val == null) {
            return true;
        } else if ("".equals(val.trim()) || "null".equals(val) || "undefined".equals(val) || "[]".equals(val) || "{}".equals(val)) {
            return true;
        }
        return false;
    }

    public static String checkStrNull(Object val) {
        if (val == null) {
            return "";
        } else {
            if (val instanceof String) {
                if ("".equals(val) || "null".equals(val) || "undefined".equals(val) || "[]".equals(val) || "{}".equals(val)) {
                    return "";
                } else {
                    return String.valueOf(val).trim();
                }
            } else {
                String res = String.valueOf(val);
                if (res.indexOf("0E-") >= 0) {
                    res = "0";
                }
                return res;
            }
        }
    }

    public static String getNowTime() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = df.format(new Date());
        return nowTime;
    }

    //SQL符合规范则返回true，否则返回flase
    public static boolean sqlCheck(String str) {
        boolean res = true;
        if (str == null || "".equals(str) || "null".equals(str) || "undefined".equals(str)) {
            return res;
        }
        str = str.toLowerCase();
        String inj_str = "'| and |exec |insert |select |delete |update |count| * |%|chr(|mid(|master|truncate|char(|declare |;| or |--|(+)|,";
        String[] inj_stra = inj_str.split("\\|");
        for (int i = 0; i < inj_stra.length; i++) {
            if (str.indexOf(inj_stra[i]) >= 0) {
                res = false;
                break;
            }
        }
        return res;
    }

    //没有特殊字符
    public static boolean strIsWord(String str) {
        boolean res = true;
        if (str == null || "".equals(str) || "null".equals(str) || "undefined".equals(str)) {
            return res;
        }
        Pattern pattern = Pattern.compile("^[a-zA-Z0-9]+$");
        res = pattern.matcher(str).matches();
        return res;
    }

    //获得随机字符串
    public static String getRandomString(int length) {
        StringBuffer buffer = new StringBuffer("1234567890abcdefghijklmnopqrstuvwxyz");
        StringBuffer sb = new StringBuffer();
        Random r = new Random();
        int range = buffer.length();
        for (int i = 0; i < length; i++) {
            sb.append(buffer.charAt(r.nextInt(range)));
        }
        return sb.toString();
    }

    //返回{状态，压缩图片名，大小}，状态：0文件不存在，1压缩图保存成功，2压缩图异常，3图片格式不正确
    public static String[] uploadTupian(MultipartFile file, String upPath, int yasuosize) {
        String[] res = {"0", "", "0"};
        if (file != null && !file.isEmpty()) {
            File ftemp = null;
            try {
                ftemp = File.createTempFile("tmp", null);
                file.transferTo(ftemp);
                ftemp.deleteOnExit();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (ftemp == null) {
                res[0] = "0";
            } else {
                String nameflag = ShareFunction.getRandomString(20);

                int type = 0;//0可以压缩，1不能压缩
                String tupiantype = file.getContentType();
                tupiantype = tupiantype.substring(tupiantype.indexOf("/") + 1, tupiantype.length());
                tupiantype = tupiantype.toLowerCase();
                if (!"jpg".equals(tupiantype) && !"png".equals(tupiantype) && !"jpeg".equals(tupiantype)) {
                    if ("gif".equals(tupiantype)) {
                        type = 1;
                    } else {
                        res[0] = "3";
                        return res;
                    }
                }
                if ("jpeg".equals(tupiantype)) {
                    tupiantype = "jpg";
                }
                String nameend = "." + tupiantype;
                SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
                String Time2 = df2.format(new Date());
                String newfilename = Time2 + nameflag + nameend;
                try {
                    FileOutputStream fos = new FileOutputStream(upPath + newfilename);
                    FileInputStream fis = new FileInputStream(ftemp);
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while ((len = fis.read(buffer)) > 0) {
                        fos.write(buffer, 0, len);
                    }
                    fis.close();
                    fos.close();
                } catch (IOException e) {
                    res[0] = "2";
                    return res;
                }
                res[0] = "1";
                res[1] = newfilename;

                if (type == 0) {
                    if (yasuosize <= 0) {
                        yasuosize = 80;// KB，比这大才压缩
                    }
                    long size = ftemp.length();
                    double scale = 1.0d;
                    if (size >= yasuosize * 1024) {
                        if (size > 0) {
                            scale = (yasuosize * 1024f) / size;
                        }
                    }
                    try {
                        // Thumbnails.of(filePathName).size(width,height).toFile(thumbnailFilePathName);
                        if (size > yasuosize * 1024) {
                            //Thumbnails.of(lasttupianpath).scale(1f).outputFormat(tupiantype).toFile(thumbnailFilePathName);
                            String lasttupianpath = upPath + newfilename;
                            String thumbnailFileName = Time2 + nameflag + "ys" + nameend;
                            String thumbnailFilePathName = upPath + thumbnailFileName;
                            Thumbnails.of(lasttupianpath).scale(1f).outputQuality(scale).outputFormat(tupiantype).toFile(thumbnailFilePathName);
                            res[0] = "1";
                            res[1] = thumbnailFileName;

                            lasttupianpath = lasttupianpath.replace("%20", " ");
                            File f1 = new File(lasttupianpath);
                            if (f1.exists()) {
                                f1.delete();
                            }
                        }
                    } catch (Exception e1) {
                        res[0] = "2";
                        return res;
                    }
                }
                File file2 = new File(upPath + res[1]);
                if (file2.length() >= 1024) {
                    long filelen = file2.length() / 1024;
                    if (filelen < 1024) {
                        res[2] = filelen + "K";
                    } else {
                        BigDecimal size = new BigDecimal(filelen);
                        BigDecimal bd1024 = new BigDecimal("1024");
                        res[2] = size.divide(bd1024, 1, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString() + "M";
                    }
                }
            }
        }
        return res;
    }


    //返回{状态，压缩图片名，大小}，状态：0文件不存在，1压缩图保存成功，2压缩图异常，3图片格式不正确
    public static String[] uploadTupian2(MultipartFile file, String upPath, String name, int yasuosize) {
        String[] res = {"0", "", "0"};
        if (file != null && !file.isEmpty()) {
            File ftemp = null;
            try {
                ftemp = File.createTempFile("tmp", null);
                file.transferTo(ftemp);
                ftemp.deleteOnExit();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (ftemp == null) {
                res[0] = "0";
            } else {
                String nameflag = name;

                int type = 0;//0可以压缩，1不能压缩
                String tupiantype = file.getContentType();
                tupiantype = tupiantype.substring(tupiantype.indexOf("/") + 1, tupiantype.length());
                tupiantype = tupiantype.toLowerCase();
                if (!"jpg".equals(tupiantype) && !"png".equals(tupiantype) && !"jpeg".equals(tupiantype)) {
                    if ("gif".equals(tupiantype)) {
                        type = 1;
                    } else {
                        res[0] = "3";
                        return res;
                    }
                }
                if ("jpeg".equals(tupiantype)) {
                    tupiantype = "jpg";
                }
                String nameend = "." + tupiantype;
                String newfilename = nameflag + nameend;
                try {
                    FileOutputStream fos = new FileOutputStream(upPath + newfilename);
                    FileInputStream fis = new FileInputStream(ftemp);
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while ((len = fis.read(buffer)) > 0) {
                        fos.write(buffer, 0, len);
                    }
                    fis.close();
                    fos.close();
                } catch (IOException e) {
                    res[0] = "2";
                    return res;
                }
                res[0] = "1";
                res[1] = newfilename;

                if (type == 0) {
                    if (yasuosize <= 0) {
                        yasuosize = 80;// KB，比这大才压缩
                    }
                    long size = ftemp.length();
                    double scale = 1.0d;
                    if (size >= yasuosize * 1024) {
                        if (size > 0) {
                            scale = (yasuosize * 1024f) / size;
                        }
                    }
                    try {
                        // Thumbnails.of(filePathName).size(width,height).toFile(thumbnailFilePathName);
                        if (size > yasuosize * 1024) {
                            //Thumbnails.of(lasttupianpath).scale(1f).outputFormat(tupiantype).toFile(thumbnailFilePathName);
                            String lasttupianpath = upPath + newfilename;
                            String thumbnailFileName = nameflag + "ys" + nameend;
                            String thumbnailFilePathName = upPath + thumbnailFileName;
                            Thumbnails.of(lasttupianpath).scale(1f).outputQuality(scale).outputFormat(tupiantype).toFile(thumbnailFilePathName);
                            res[0] = "1";
                            res[1] = thumbnailFileName;

                            lasttupianpath = lasttupianpath.replace("%20", " ");
                            File f1 = new File(lasttupianpath);
                            if (f1.exists()) {
                                f1.delete();
                            }
                        }
                    } catch (Exception e1) {
                        res[0] = "2";
                        return res;
                    }
                }
                File file2 = new File(upPath + res[1]);
                if (file2.length() >= 1024) {
                    long filelen = file2.length() / 1024;
                    if (filelen < 1024) {
                        res[2] = filelen + "K";
                    } else {
                        BigDecimal size = new BigDecimal(filelen);
                        BigDecimal bd1024 = new BigDecimal("1024");
                        res[2] = size.divide(bd1024, 1, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString() + "M";
                    }
                }
            }
        }
        return res;
    }

    //返回{状态，视频名,视频大小}，状态：0文件不存在，1保存成功，2异常，3格式不正确
    public static String[] uploadVideo(MultipartFile vid, String upPath) {
        String[] res = {"0", "", "0", "0", "00:00"};
        if (vid != null && !vid.isEmpty()) {
            File ftemp = null;
            try {
                ftemp = File.createTempFile("tmp", null);
                vid.transferTo(ftemp);
                ftemp.deleteOnExit();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (ftemp == null) {
                res[0] = "0";
            } else {
                String uploadFileName = vid.getOriginalFilename();
                String nameflag = ShareFunction.getRandomString(20);
                String nameend = uploadFileName.substring(uploadFileName.lastIndexOf("."), uploadFileName.length());
                String tupiantype = nameend.substring(1, nameend.length());
                if (!"mp4".equals(tupiantype) && !"ogg".equals(tupiantype) && !"mov".equals(tupiantype)) {
                    res[0] = "3";
                    return res;
                }
                SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
                String Time2 = df2.format(new Date());
                String newfilename = Time2 + nameflag + nameend;
                try {
                    FileOutputStream fos = new FileOutputStream(upPath + newfilename);
                    FileInputStream fis = new FileInputStream(ftemp);
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while ((len = fis.read(buffer)) > 0) {
                        fos.write(buffer, 0, len);
                    }
                    fis.close();
                    fos.close();

                    res[0] = "1";
                    res[1] = newfilename;

                    String prefix = newfilename.substring(0, newfilename.lastIndexOf("."));
                    String targetName = prefix + "ys" + ".mp4";
                    File source = new File(upPath + newfilename);
                    File target = new File(upPath + targetName);
                    if (source.exists() && source.length() < (1024 * 1024 * 1024 * 2)) {
                        try {
                            MultimediaObject object = new MultimediaObject(source);
                            AudioInfo audioInfo = object.getInfo().getAudio();

                            int maxBitRate = 128000;//最大音频比特率
                            int maxSamplingRate = 44100;//音频采样率
                            int bitRate = 800000;//视频比特率
                            int maxFrameRate = 20;//视频帧率
                            int maxWidth = 1280;//视频最大宽度

                            //音频
                            AudioAttributes audio = new AudioAttributes();
                            audio.setCodec("aac");
                            if (audioInfo.getBitRate() > maxBitRate) {
                                audio.setBitRate(new Integer(maxBitRate));
                            }
                            audio.setChannels(audioInfo.getChannels());
                            if (audioInfo.getSamplingRate() > maxSamplingRate) {
                                audio.setSamplingRate(maxSamplingRate);
                            }

                            //视频
                            VideoInfo videoInfo = object.getInfo().getVideo();
                            VideoAttributes video = new VideoAttributes();
                            video.setCodec("h264");
                            if (videoInfo.getBitRate() > bitRate) {
                                video.setBitRate(bitRate);
                            }
                            if (videoInfo.getFrameRate() > maxFrameRate) {
                                video.setFrameRate(maxFrameRate);
                            }
                            int width = videoInfo.getSize().getWidth();
                            int height = videoInfo.getSize().getHeight();
                            if (width > maxWidth) {
                                float rat = (float) width / maxWidth;
                                video.setSize(new VideoSize(maxWidth, (int) (height / rat)));
                            }

                            EncodingAttributes attr = new EncodingAttributes();
                            attr.setFormat("mp4");
                            attr.setAudioAttributes(audio);
                            attr.setVideoAttributes(video);

                            Encoder encoder = new Encoder();
                            encoder.encode(new MultimediaObject(source), target, attr);
                            res[1] = targetName;
                            source.delete();
                        } catch (Exception e) {
                            System.out.println("视频压缩失败");
                        }
                    }
                    try {
                        File file = new File(upPath + res[1]);
                        if (file.length() >= 1024) {
                            BigDecimal size = new BigDecimal(file.length());
                            BigDecimal bd1m = new BigDecimal("1048576");//1M
                            res[2] = size.divide(bd1m, 1, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString() + "M";
                        }
                        MultimediaObject multimediaObject = new MultimediaObject(file);
                        MultimediaInfo info = multimediaObject.getInfo();
                        int duration = (int) (info.getDuration() / 1000);
                        res[3] = String.valueOf(duration);
                        String durationText = "";
                        int second = duration % 60;
                        int minute = (duration % 3600) / 60;
                        int hour = duration / 3600;
                        if (hour > 0) {
                            if (hour < 10) {
                                durationText += "0";
                            }
                            durationText += hour + ":";
                        }
                        if (minute < 10) {
                            durationText += "0";
                        }
                        durationText += minute + ":";
                        if (second < 10) {
                            durationText += "0";
                        }
                        durationText += second;
                        res[4] = durationText;
                    } catch (Exception e) {
                        System.out.println("视频信息获取失败");
                    }
                } catch (IOException e) {
                    res[0] = "2";
                    return res;
                }
                res[0] = "1";
                res[1] = newfilename;
            }
        }
        return res;
    }

    //返回{状态，新文件名，原文件名，文件大小}，状态：0文件不存在，1保存成功，2异常，3格式不正确
    public static String[] uploadFile(MultipartFile fujian, String upPath) {
        String[] res = {"0", "", "", "", ""};
        if (fujian != null && !fujian.isEmpty()) {
            File ftemp = null;
            try {
                ftemp = File.createTempFile("tmp", null);
                fujian.transferTo(ftemp);
                ftemp.deleteOnExit();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (ftemp == null) {
                res[0] = "0";
            } else {
                String uploadFileName = fujian.getOriginalFilename();
                res[2] = uploadFileName;
                String nameflag = ShareFunction.getRandomString(20);
                String nameend = uploadFileName.substring(uploadFileName.lastIndexOf("."), uploadFileName.length());
                String tupiantype = nameend.substring(1, nameend.length());
                String tupiantypeTemp = tupiantype.toLowerCase();
                if ("vbs".equals(tupiantypeTemp) || "vbe".equals(tupiantypeTemp) || "js".equals(tupiantypeTemp)
                        || "jse".equals(tupiantypeTemp) || "wsh".equals(tupiantypeTemp) || "wsf".equals(tupiantypeTemp)
                        || "exe".equals(tupiantypeTemp)) {
                    res[0] = "3";
                    return res;
                }
                SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
                String Time2 = df2.format(new Date());
                String newfilename = Time2 + nameflag + nameend;
                try {
                    FileOutputStream fos = new FileOutputStream(upPath + newfilename);
                    FileInputStream fis = new FileInputStream(ftemp);
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while ((len = fis.read(buffer)) > 0) {
                        fos.write(buffer, 0, len);
                    }
                    fis.close();
                    fos.close();
                } catch (IOException e) {
                    res[0] = "2";
                    return res;
                }
                res[0] = "1";
                res[1] = newfilename;
                String sizeStr = "";
                long sizeLen = ftemp.length();
                if (sizeLen < 1024) {
                    sizeStr = sizeLen + "B";
                } else if (sizeLen < (1024 * 1024)) {
                    sizeStr = sizeLen / 1024 + "K";
                } else {
                    BigDecimal size = new BigDecimal(sizeLen);
                    BigDecimal bd1m = new BigDecimal("1048576");//1M
                    sizeStr = size.divide(bd1m, 1, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString() + "M";
                }
                res[3] = sizeStr;
                res[4] = tupiantypeTemp;
            }
        }
        return res;
    }

    //检测字符串是否为数字
    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    //返回随机整数
    public static int getRandomInt(int minInt, int maxInt) {
        int res = 0;
        res = (int) (minInt + Math.random() * (maxInt - minInt + 1));
        return res;
    }

    //返回随机整数字符串
    public static String getRandomIntStr(int length) {
        StringBuffer buffer = new StringBuffer("1234567890");
        StringBuffer sb = new StringBuffer();
        Random r = new Random();
        int range = buffer.length();
        for (int i = 0; i < length; i++) {
            sb.append(buffer.charAt(r.nextInt(range)));
        }
        return sb.toString();
    }

    //返回随机交易单号
    public static String getRandomSerialid(int length) {
        StringBuffer buffer = new StringBuffer("1234567890");
        StringBuffer sb = new StringBuffer();
        Random r = new Random();
        int range = buffer.length();
        for (int i = 0; i < length; i++) {
            sb.append(buffer.charAt(r.nextInt(range)));
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String time1 = df.format(new Date());
        return time1 + sb.toString();
    }

    //删除文件
    public static void deleteFile(String upPath, String imgName) {
        if (!ShareFunction.strIsNull(imgName) && !ShareFunction.strIsNull(upPath)) {
            File deletefile = new File(upPath + imgName);
            if (deletefile.exists()) {
                deletefile.delete();
            }
        }
    }

    private static Object checkObjNull(Object val) {
        if (val == null) {
            return "";
        } else {
            if (val instanceof String) {
                if ("".equals(val) || "null".equals(val) || "undefined".equals(val) || "[]".equals(val) || "{}".equals(val)) {
                    return "";
                } else {
                    return String.valueOf(val).trim();
                }
            } else {
                if (String.valueOf(val).indexOf("0E-") >= 0) {
                    return 0;
                }
                return val;
            }
        }
    }
    //将类转化为map（用户）
//	public static HashMap<String, Object> objToMap(Object obj) {
//		HashMap<String, Object> map1 = new HashMap<String, Object>();
//		try{
//			if(obj != null){
//				Field[] fields = obj.getClass().getDeclaredFields();
//				String className = "";
//				try{
//					String classNameFull = obj.getClass().getName();
//					className = classNameFull.substring(classNameFull.lastIndexOf(".")+1, classNameFull.length()).toLowerCase();
//				}catch (Exception e) {
//					System.out.println("获取类名失败");
//				}
//				for(int m=0;m<fields.length;m++){
//					Field field = fields[m];
//					field.setAccessible(true);
//					if(!"id".equals(field.getName()) && !"serialVersionUID".equals(field.getName())
//							&& !"del".equals(field.getName()) && !"ipaddress".equals(field.getName())
//							&& !"priority".equals(field.getName()) && !"showFlag".equals(field.getName())){
//						Object val = checkObjNull(field.get(obj));
//						if("introduce".equals(field.getName())){
//							val = wxRichtext(checkStrNull(field.get(obj)));
//						}else if("pic".equals(field.getName()) || "pic1".equals(field.getName()) || "pic2".equals(field.getName())
//								|| "pic3".equals(field.getName()) || "pic4".equals(field.getName()) || "pic5".equals(field.getName())
//								|| "pic6".equals(field.getName()) || "headpic".equals(field.getName()) || "vid".equals(field.getName())){
//							if(!strIsNull(className) && val != null){
//								val = wxPicUrl(className, String.valueOf(val));
//							}
//						}
//						map1.put(field.getName(), val);
//					}
//				}
//			}
//		}catch (Exception e) {
//			System.out.println("类转化为map出错");
//			e.printStackTrace();
//		}
//		return map1;
//	}
    //将类转化为map（管理员）
//	public static HashMap<String, Object> adminObjToMap(Object obj) {
//		HashMap<String, Object> map1 = new HashMap<String, Object>();
//		try{
//			if(obj != null){
//				Field[] fields = obj.getClass().getDeclaredFields();
//				String className = "";
//				try{
//					String classNameFull = obj.getClass().getName();
//					className = classNameFull.substring(classNameFull.lastIndexOf(".")+1, classNameFull.length()).toLowerCase();
//				}catch (Exception e) {
//					System.out.println("获取类名失败");
//				}
//				for(int m=0;m<fields.length;m++){
//					Field field = fields[m];
//					field.setAccessible(true);
//					if(!"serialVersionUID".equals(field.getName())){
//						String val = checkStrNull(field.get(obj));
//						if(!strIsNull(val)){
//							if("showFlag".equals(field.getName())){
//								val = getShowFlagStr(Integer.valueOf(val));
//							}else if("verifyFlag".equals(field.getName())){
//								val = getVerifyFlagStr(Integer.valueOf(val));
//							}else if("payFlag".equals(field.getName())){
//								val = getPayFlagStr(Integer.valueOf(val));
//							}else if("openFlag".equals(field.getName())){
//								val = getOpenFlagStr(Integer.valueOf(val));
//							}else if("topFlag".equals(field.getName())){
//								val = getTopFlagStr(Integer.valueOf(val));
//							}else if("authority".equals(field.getName())){
//								val = getAuthorityStr(Integer.valueOf(val));
//							}else if("pic".equals(field.getName()) || "pic1".equals(field.getName()) || "pic2".equals(field.getName())
//									|| "pic3".equals(field.getName()) || "pic4".equals(field.getName()) || "pic5".equals(field.getName())
//									|| "pic6".equals(field.getName()) || "headpic".equals(field.getName())){
//								if(!strIsNull(className)){
//									val = getPicUrlStr(className, val);
//								}
//							}else if("vid".equals(field.getName())){
//								if(!strIsNull(className)){
//									val = getVidOneStr(className, val);
//								}
//							}
//						}
//						map1.put(field.getName(), val);
//					}
//				}
//			}
//		}catch (Exception e) {
//			System.out.println("类转化为map出错");
//			e.printStackTrace();
//		}
//		return map1;
//	}

    //检测字符符串是否满足位数，并在前面补零
    public static String buLing(String str, int weishu) {
        if (str == null || "".equals(str) || "null".equals(str)) {
            return "";
        } else {
            if (str.length() >= weishu) {
                return str;
            } else {
                String ling = "";
                for (int i = 0; i < (weishu - str.length()); i++) {
                    ling += "0";
                }
                str = ling + str;
                return str;
            }
        }
    }

    //校验时间格式是否规范，未补零将补零，溢出范围自动取最值
    public static String checkTime(String time, String timeFormat) {
        String res = "";//yyyy-MM-dd HH:mm:ss
        boolean safeok = true;
        if (safeok && (time == null || "".equals(time) || "null".equals(time))) {
            safeok = false;
        }
        if (safeok && (timeFormat == null || "".equals(timeFormat) || "null".equals(timeFormat))) {
            safeok = false;
        }
        if (safeok) {
            try {
                if ("HH:mm".equals(timeFormat)) {
                    String timeSplit[] = time.split(":");
                    if (timeSplit == null || timeSplit.length != 2) {
                        safeok = false;
                    } else {
                        String timeSplit1 = timeSplit[0];
                        String timeSplit2 = timeSplit[1];
                        if (isInteger(timeSplit1) && isInteger(timeSplit2)) {
                            int timeSplit1Num = Integer.valueOf(timeSplit1);
                            int timeSplit2Num = Integer.valueOf(timeSplit2);
                            if (timeSplit1Num > 23) {
                                timeSplit1Num = 23;
                                timeSplit2Num = 59;
                            } else if (timeSplit1Num < 0) {
                                timeSplit1Num = 0;
                                timeSplit2Num = 0;
                            }
                            if (timeSplit2Num > 59) {
                                timeSplit2Num = 59;
                            } else if (timeSplit2Num < 0) {
                                timeSplit2Num = 0;
                            }
                            timeSplit1 = String.valueOf(timeSplit1Num);
                            timeSplit2 = String.valueOf(timeSplit2Num);
                            res = buLing(timeSplit1, 2) + ":" + buLing(timeSplit2, 2);
                        }
                    }
                } else if ("yyyy-MM-dd HH:mm".equals(timeFormat)) {
                    //校验年月日
                    String datatimeSplit[] = time.split(" ");
                    if (datatimeSplit == null || datatimeSplit.length != 2) {
                        safeok = false;
                    } else {
                        String dataSplit[] = datatimeSplit[0].split("-");
                        if (dataSplit == null || dataSplit.length != 3) {
                            safeok = false;
                        } else {
                            String dataSplit1 = dataSplit[0];
                            String dataSplit2 = dataSplit[1];
                            String dataSplit3 = dataSplit[2];
                            if (isInteger(dataSplit1) && isInteger(dataSplit2) && isInteger(dataSplit3)) {
                                int dataSplit2Num = Integer.valueOf(dataSplit2);
                                int dataSplit3Num = Integer.valueOf(dataSplit3);
                                if (dataSplit2Num > 12) {
                                    dataSplit2Num = 12;
                                }
                                if (dataSplit3Num > 31) {
                                    dataSplit3Num = 31;
                                }
                                dataSplit2 = String.valueOf(dataSplit2Num);
                                dataSplit3 = String.valueOf(dataSplit3Num);
                                res = dataSplit1 + "-" + buLing(dataSplit2, 2) + "-" + buLing(dataSplit3, 2);
                            } else {
                                safeok = false;
                            }
                        }

                        if (safeok) {
                            //校验时分
                            String timeSplit[] = datatimeSplit[1].split(":");
                            if (timeSplit == null || timeSplit.length != 2) {
                                safeok = false;
                            } else {
                                String timeSplit1 = timeSplit[0];
                                String timeSplit2 = timeSplit[1];
                                if (isInteger(timeSplit1) && isInteger(timeSplit2)) {
                                    int timeSplit1Num = Integer.valueOf(timeSplit1);
                                    int timeSplit2Num = Integer.valueOf(timeSplit2);
                                    if (timeSplit1Num > 24) {
                                        timeSplit1Num = 23;
                                        timeSplit2Num = 59;
                                    } else if (timeSplit1Num < 0) {
                                        timeSplit1Num = 0;
                                        timeSplit2Num = 0;
                                    }
                                    if (timeSplit2Num > 59) {
                                        timeSplit2Num = 59;
                                    } else if (timeSplit2Num < 0) {
                                        timeSplit2Num = 0;
                                    }
                                    timeSplit1 = String.valueOf(timeSplit1Num);
                                    timeSplit2 = String.valueOf(timeSplit2Num);
                                    res = res + " " + buLing(timeSplit1, 2) + ":" + buLing(timeSplit2, 2);
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                safeok = false;
            }
        }
        return res;
    }

    public static void checkMapNull(HashMap<String, Object> map) {
        if (map != null) {
            if (map.size() > 0) {
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    if (entry.getValue() == null) {
                        map.put(entry.getKey(), "");
                    }
                }
            }
        }
    }

    //获得随机邀请码
    public static String getRandomInviteCode(int length) {
        String res = "";
        boolean xunhuan = true;
        StringBuffer buffer = new StringBuffer("2345678ABCDEFGHJKMNPQRSTVWXY");
        StringBuffer sb = new StringBuffer();
        Random r = new Random();
        while (xunhuan) {
            xunhuan = false;
            int range = buffer.length();
            for (int i = 0; i < length; i++) {
                sb.append(buffer.charAt(r.nextInt(range)));
            }
            res = sb.toString();
            sb.delete(0, length);
        }
        return res;
    }

    //获得两simple日期之间的simple日期
    public static List<String> getBetweenDates(String startDate, String endDate) {
        List<String> datelist = new ArrayList<String>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date_start = sdf.parse(startDate);
            Date date_end = sdf.parse(endDate);
            Date date = date_start;
            Calendar cd = Calendar.getInstance();//用Calendar 进行日期比较判断
            while (date.getTime() <= date_end.getTime()) {
                datelist.add(sdf.format(date));
                cd.setTime(date);
                cd.add(Calendar.DATE, 1);//增加一天 放入集合
                date = cd.getTime();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return datelist;
    }

    //date类型转化为String类型
    public static String dateToString(Date date) {
        String time = "";
        if (date != null) {
            try {
                SimpleDateFormat formater = new SimpleDateFormat();
                formater.applyPattern("yyyy-MM-dd HH:mm:ss");
                time = formater.format(date);
            } catch (Exception e) {
                System.out.println("date转String异常！");
            }
        }
        return time;
    }

    //计算两日期相差天数
    public static int daysBetween(String startDate, String endDate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(startDate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(endDate));
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }

    //计算两日期相差分钟数
    public static int minuteBetween(String startdate, String enddate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(startdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(enddate));
        long time2 = cal.getTimeInMillis();
        long between_minute = (time2 - time1) / (1000 * 60);
        return Integer.parseInt(String.valueOf(between_minute));
    }

    //某日期前或后几天的日期列表
    public static List<String> getDatesByTianShu(String datetime, int tianshu) throws ParseException {
        List<String> datelist = new ArrayList<String>();
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = format2.parse(datetime);
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(date1);
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        calendar1.add(Calendar.DATE, tianshu);
        String datetime2 = sdf1.format(calendar1.getTime());
        if (tianshu < 0) {
            datelist = getBetweenDates(datetime2, datetime);
        } else {
            datelist = getBetweenDates(datetime, datetime2);
        }
        return datelist;
    }

    //某日期前或后第几天的日期
    public static String getDateLast(String datetime, int tianshu) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(datetime, new ParsePosition(0));
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, tianshu);
        Date date1 = calendar.getTime();
        String res = sdf.format(date1);
        return res;
    }

    //某时间前或后第几天的时间
    public static String getDateTimeLast(String datetime, int tianshu) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sdf.parse(datetime, new ParsePosition(0));
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, tianshu);
        Date date1 = calendar.getTime();
        String res = sdf.format(date1);
        return res;
    }

    //某时间前或后几分钟的时间
    public static String getDateTimeLastMinute(String datetime, int minute) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sdf.parse(datetime, new ParsePosition(0));
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MINUTE, minute);
        Date date1 = calendar.getTime();
        String res = sdf.format(date1);
        return res;
    }

    //获得星期几
    public static int dayForWeek(String nowTime) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date tmpDate = format.parse(nowTime);
        Calendar cal = Calendar.getInstance();
        int[] weekDays = {7, 1, 2, 3, 4, 5, 6};
        try {
            cal.setTime(tmpDate);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        return weekDays[w];
    }

//	public static String replaceTextUrl(String mycontent) {
//		if(mycontent!=null&&!"".equals(mycontent)&&!"null".equals(mycontent)){
//			mycontent = mycontent.replace(DefaultData.SourceURL, "datasource/");
//		}else{
//			mycontent = "";
//		}
//		return mycontent;
//	}
//	public static void deleteTextPic(HttpServletRequest request,String lastIntroduce,String mycontent) {
//		if(lastIntroduce!=null&&!"".equals(lastIntroduce)&&!"null".equals(lastIntroduce)&&request!=null){
//			try{
//				List<String> newPicUrlList = new ArrayList<String>();
//				if(mycontent!=null&&!"".equals(mycontent)&&!"null".equals(mycontent)){
//					int xiabiao2 = 0;
//					int xiabiao2End = 0;
//					while(true){
//						int introduceIndex2 = mycontent.indexOf("<img src=\"datasource/textpic/", xiabiao2);
//						if(introduceIndex2>=0){
//							int introduceIndex2End = mycontent.indexOf("\" title=", xiabiao2End+1);
//							if(introduceIndex2End>=xiabiao2){
//								String picUrl = mycontent.substring(introduceIndex2+29, introduceIndex2End);
//								newPicUrlList.add(picUrl);
//							}
//							xiabiao2 = introduceIndex2 + 1;
//							xiabiao2End = introduceIndex2End + 1;
//						}else{
//							break;
//						}
//					}
//				}
//
//				String upPath = request.getServletContext().getRealPath("datasource/textpic/");
//				upPath = upPath.replace("%20", " ");
//				if(upPath!=null&&!"".equals(upPath)&&!"null".equals(upPath)){
//					int xiabiao = 0;
//					int xiabiaoEnd = 0;
//					while(true){
//						int introduceIndex = lastIntroduce.indexOf("<img src=\"datasource/textpic/", xiabiao);
//						if(introduceIndex>=0){
//							int introduceIndexEnd = lastIntroduce.indexOf("\" title=", xiabiaoEnd+1);
//							if(introduceIndexEnd>=xiabiao){
//								String picUrl = lastIntroduce.substring(introduceIndex+29, introduceIndexEnd);
//								if(newPicUrlList==null || newPicUrlList.size()==0 || !newPicUrlList.contains(picUrl)){
//									File deletefile1 = new File(upPath + picUrl);
//									if(deletefile1.exists()){
//										deletefile1.delete();
//									}
//								}
//							}
//							xiabiao = introduceIndex + 1;
//							xiabiaoEnd = introduceIndexEnd + 1;
//						}else{
//							break;
//						}
//					}
//				}
//			}catch(Exception e){
//				System.out.println("删除富文本图片异常！");
//			}
//		}
//	}

    //复制图片至另一个目录
    public static String copyPic(String picPath1, String picPath2) {
        String res = "";
        if (!strIsNull(picPath1) && !strIsNull(picPath2)) {
            try {
                res = getRandomString(40) + picPath1.substring(picPath1.lastIndexOf("."), picPath1.length());
                InputStream in = new FileInputStream(picPath1);
                byte[] b = new byte[in.available()];
                in.read(b);
                OutputStream out = new FileOutputStream(picPath2 + res);
                out.write(b);
                in.close();
                out.close();
            } catch (Exception e) {
                System.out.println("复制图片异常");
            }
        }
        return res;
    }

    //数据统一加密
//	public static String myEncrypt(String strSrc){
//		if(strSrc==null||"".equals(strSrc)||"null".equals(strSrc)){
//			return "";
//		}
//		String res = strSrc;
//		for(int p=0;p<8;p++){
//			res = SHA256.Encrypt(res);
//			res = MD5.md5upper(res);
//		}
//		return res;
//	}

    //身份证号格式校验
    public static boolean verIdcardForm(String num) {
        String reg = "^\\d{15}$|^\\d{17}[0-9Xx]$";
        if (!num.matches(reg)) {
            return false;
        }
        return true;
    }

    //当前时间是否在某时间区间内（0在范围内，1未开始，2已结束）
    public static int checkNowInDatetime(String startTime, String endTime) {
        int res = 0;
        if (!ShareFunction.strIsNull(startTime) || !ShareFunction.strIsNull(endTime)) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String nowTime = df.format(new Date());
            if (!ShareFunction.strIsNull(startTime)) {
                if (nowTime.compareTo(startTime) < 0) {
                    res = 1;
                }
            }
            if (!ShareFunction.strIsNull(endTime)) {
                if (nowTime.compareTo(endTime) > 0) {
                    res = 2;
                }
            }
        }
        return res;
    }

    //判断网络资源是否存在
    public static boolean checkFileUrlExist(String fileUrl) {
        boolean res = false;
        if (strIsNull(fileUrl)) {
            return res;
        }
        try {
            URL url = new URL(fileUrl);
            URLConnection uc = url.openConnection();
            InputStream in = uc.getInputStream();
            res = true;
            in.close();
        } catch (Exception e) {
        }
        return res;
    }

    //列表图片
//	public static String getPicUrlStr(String shiti,String picName){
//		String res = "";
//		if(!strIsNull(shiti) && !strIsNull(picName)){
//			res = DefaultData.SourceURL+shiti+"/"+picName;
//		}
//		return res;
//	}
    //列表a标签
    public static String getDetailStr(String shiti, String mdid, String msg) {
        String res = "";
        if (!strIsNull(shiti) && !strIsNull(mdid) && !strIsNull(msg)) {
            res = "<a onclick=\"opendetail('" + shiti + "','" + mdid + "')\" href=\"javascript:;\" class=\"acss\">" + msg + "</a>";
        }
        return res;
    }

    //颜色
    public static String getColorStr(String bgcolor, String color, String title) {
        String res = "";
        if (strIsNull(color)) {
            color = "#ffffff";
        }
        if (!strIsNull(bgcolor) && !strIsNull(color) && !strIsNull(title)) {
            res = "<div style=\"color:" + color + ";background-color:" + bgcolor + ";display:inline;padding:4px 10px;font-size:12px;\">" + title + "</div>";
        }
        return res;
    }

    //详情中图片
    public static String getPicOneStr(String shiti, String picName) {
        String res = "<div style='color:#CCCCCC;'>未上传</div>";
        if (!strIsNull(shiti) && !strIsNull(picName)) {
            res = "<img src='datasource/" + shiti + "/" + picName + "' style='height:60px;'/>";
        }
        return res;
    }

    //详情中图片（可打开）
//	public static String getPicOneStrBlank(String shiti,String picName){
//		String res = "<div style='color:#CCCCCC;'>未上传</div>";
//		if(!strIsNull(shiti) && !strIsNull(picName)){
//			res = "<a href='"+DefaultData.SourceURL+shiti+"/"+picName+"' target='_blank'><img src='datasource/"+shiti+"/"+picName+"' style='height:60px;'/></a>";
//		}
//		return res;
//	}
    //详情中的视频
    public static String getVidOneStr(String shiti, String vidName) {
        String res = "<div style='color:#CCCCCC;'>未上传</div>";
        if (!strIsNull(shiti) && !strIsNull(vidName)) {
            res = "<video src='datasource/" + shiti + "/" + vidName + "' controls='controls' style='height:100px;' />";
        }
        return res;
    }

    //转义大文本内空格换行
    public static String checkContent(String content) {
        if (strIsNull(content)) {
            content = "";
        } else {
            content = EmojiParser.parseToUnicode(content);
            content = content.replace("\n", "<br>");
            content = content.replace(" ", "&nbsp;");
        }
        return content;
    }

    //网页端富文本
//	public static String webIntroduce(String introduce){
//		if(ShareFunction.strIsNull(introduce)){
//			introduce = "<div style=\"text-align:center;margin-top:20px;color:#CCCCCC;width:100%;\">暂无介绍</div>";
//		}else{
//			introduce = introduce.replace("src=\"datasource/", "src=\""+DefaultData.SourceURL);
//			introduce = introduce.replace("<p ", "<div ");
//			introduce = introduce.replace("<p>", "<div>");
//			introduce = introduce.replace("</p>", "</div>");
//		}
//		return introduce;
//	}

    //返回显隐状态
    public static String getShowFlagStr(Integer showFlag) {
        String res = "";
        if (showFlag != null) {
            if (showFlag == 0) {
                res = "隐藏";
            } else if (showFlag == 1) {
                res = "显示";
            }
        }
        return res;
    }

    //返回显隐状态
    public static String getGrade(Integer showFlag) {
        String res = "";
        if (showFlag != null) {
            if (showFlag == 0) {
                res = "未设置";
            } else if (showFlag == 1) {
                res = "一等奖";
            } else if (showFlag == 2) {
                res = "二等奖";
            } else if (showFlag == 3) {
                res = "三等奖";
            } else if (showFlag == 4) {
                res = "四等奖";
            } else if (showFlag == 5) {
                res = "特等奖";
            } else if (showFlag == 6) {
                res = "安慰奖";
            }


        }
        return res;
    }

    //返回开闭状态
    public static String getOpenFlagStr(Integer openFlag) {
        String res = "";
        if (openFlag != null) {
            if (openFlag == 0) {
                res = "已关闭";
            } else if (openFlag == 1) {
                res = "已开启";
            }
        }
        return res;
    }

    //返回上下架状态
    public static String getOfflineFlagStr(Integer offlineFlag) {
        String res = "";
        if (offlineFlag != null) {
            if (offlineFlag == 0) {
                res = "已下架";
            } else if (offlineFlag == 1) {
                res = "上架中";
            }
        }
        return res;
    }

    //返回是否置顶
    public static String getTopFlagStr(Integer topFlag) {
        String res = "";
        if (topFlag != null) {
            if (topFlag == 0) {
                res = "未置顶";
            } else if (topFlag == 1) {
                res = "已置顶";
            }
        }
        return res;
    }

    //返回是否支付
    public static String getPayFlagStr(Integer payFlag) {
        String res = "";
        if (payFlag != null) {
            if (payFlag == 0) {
                res = "未支付";
            } else if (payFlag == 1) {
                res = "已支付";
            }
        }
        return res;
    }

    //返回是否审核
    public static String getVerifyFlagStr(Integer verifyFlag) {
        String res = "";
        if (verifyFlag != null) {
            if (verifyFlag == 0) {
                res = "待审核";
            } else if (verifyFlag == 1) {
                res = "已通过";
            } else if (verifyFlag == 2) {
                res = "未通过";
            }
        }
        return res;
    }

    //返回是否
    public static String getIsStr(Integer isFlag) {
        String res = "";
        if (isFlag != null) {
            if (isFlag == 0) {
                res = "否";
            } else if (isFlag == 1) {
                res = "是";
            }
        }
        return res;
    }

    //返回是否有权限
    public static String getAuthorityStr(Integer authority) {
        String res = "";
        if (authority != null) {
            if (authority == 0) {
                res = "正常";
            } else if (authority == 1) {
                res = "封号";
            }
        }
        return res;
    }

    //返回时间是多久前
    public static String getTimeLastStr(String createtime) throws ParseException {
        String res = "";
        if (!strIsNull(createtime)) {
            String nowTime = getNowTime();
            int fen = minuteBetween(createtime, nowTime);
            if (fen < 60) {
                res = fen + "分钟前";
            } else if (fen >= 60 && fen < 660) {
                res = (fen / 60) + "小时前";
            } else {
                res = createtime.substring(5, 16);
            }
        }
        return res;
    }

    //加密手机号
    public static String cutPhone(String phone) throws Exception {
        if (ShareFunction.strIsNull(phone)) {
            return "";
        }
        if (phone.length() >= 11) {
            phone = phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4, phone.length());
        } else if (phone.length() >= 4) {
            phone = phone.substring(0, 3) + "****";
        } else {
            phone = "****";
        }
        return phone;
    }

    //返回图片全路径
//	public static String wxPicUrl(String shiti,String pic){
//		String res = "";
//		if(!strIsNull(pic)){
//			res = DefaultData.SourceURL + shiti + "/" + pic;
//		}
//		return res;
//	}
//	public static String wxRichtext(String introduce){
//		String res = "";
//		if(!strIsNull(introduce)){
//			res = introduce.replace("src=\"datasource/", "class=\"richimg\" src=\""+DefaultData.SourceURL);
//			res = res.replace("<p ", "<div ");
//			res = res.replace("<p>", "<div>");
//			res = res.replace("</p>", "</div>");
//		}else{
//			res = "<div style=\"text-align:center;margin-top:40px;margin-bottom:40px;color:#eeeeee;\">暂无介绍</div>";
//		}
//		return res;
//	}


    public static void copy(File source, File fil) throws IOException {
// 判断源目录是不是一个目录
        if (!source.isDirectory()) {
//如果不是目录就不复制
            return;
        }
//创建目标目录的file对象
        if (!fil.exists()) {
//不存在就创建文件夹
            fil.mkdir();
        } else {
            return;
        }
        //如果源文件存在就复制
        if (source.exists()) {
            // 获取源目录下的File对象列表
            File[] files = source.listFiles();

            for (File file2 : files) {
//新文件夹的路径
                File file4 = new File(fil + File.separator + file2.getName());

                if (file2.isDirectory()) {
                    copy(file2, file4);
                }
                if (file2.isFile()) {
                    FileInputStream in = new FileInputStream(file2);
                    FileOutputStream out = new FileOutputStream(file4);

                    byte[] bs = new byte[1026];

                    int count = 0;
//循环把源文件的内容写入新文件
                    while ((count = in.read(bs, 0, bs.length)) != -1) {
                        out.write(bs, 0, count);
                    }
                    System.out.println("复制成功");

//关闭流
                    out.flush();
                    out.close();
                    in.close();
                }
            }
        }
    }

}
